import pygame
from .. import tools,setup
from .. import constants as C

class Player(pygame.sprite.Sprite):
    def __init__(self,name):
        pygame.sprite.Sprite.__init__(self)
        self.name=name
        self.setupStates()
        self.setupVelocities()
        self.setupTimers()
        self.loadImages()

        self.frameIndex=0
        self.image=self.frames[self.frameIndex]
        self.rect=self.image.get_rect()

    def setupStates(self):
        self.faceRight=True
        self.dead=False
        self.big=False
    def setupVelocities(self):
        self.xVel=0
        self.yVel=0
    def setupTimers(self):
        self.walkingTimer=0
        self.transitionTioner=0#变身时长
    def loadImages(self):
        sheet = setup.GRAPHICS['idle']
        self.rightFrames=[]
        self.leftFrames = []
        self.upFrames = []
        self.downFrames = []

        frameRects=[(0,0,32,64),(32,0, 32, 64),(64,0, 32, 64),(96,0, 32, 64),(128,0, 32, 64),(160,0, 32, 64),(192,0, 32, 64),(224,0, 32, 64)]

        for frameRect in frameRects:
            rightImage=tools.get_image(sheet,*frameRect,(0,0,0),C.BG_PLAYER)
            leftImage=pygame.transform.flip(rightImage,True,False)
            upImage=pygame.transform.rotate(rightImage,90)
            downImage=pygame.transform.rotate(rightImage,-90)
            self.rightFrames.append(rightImage)
            self.leftFrames.append(leftImage)
            self.upFrames.append(upImage)
            self.downFrames.append(downImage)

        #self.frames.append(tools.get_image(sheet,0,0,32,64,(0,0,0),C.BG_PLAYER))


        self.frames = self.rightFrames
        self.frameIndex=0
        self.image=self.frames[self.frameIndex]
        self.rect=self.image.get_rect()
    def update(self,keys):
        self.currentTime=pygame.time.get_ticks()
        if keys[pygame.K_d]:
            self.xVel=5
            self.yVel=0
            self.frames=self.rightFrames
        elif keys[pygame.K_a]:
            self.xVel=-5
            self.yVel=0
            self.frames=self.leftFrames
        elif keys[pygame.K_w]:
            self.xVel = 0
            self.yVel = -5
            self.frames=self.upFrames
        elif keys[pygame.K_s]:
            self.xVel=0
            self.yVel=5
            self.frames=self.downFrames
        else:
            if self.yVel<0:self.frames = self.leftFrames
            elif self.yVel>0:self.frames = self.rightFrames
            else :pass
            self.xVel = 0
            self.yVel = 0


        if self.currentTime - self.walkingTimer > 100:
            self.frameIndex += 1
            self.frameIndex = self.frameIndex % 6
            self.walkingTimer = self.currentTime
        self.image = self.frames[self.frameIndex]